<template>
  <div>
    <button @click="printDocument">打印</button>
    <div ref="printableArea">
      <!-- 将要打印的内容放在这里 -->
      <p>这是要打印的内容1。</p>
    </div>
  </div>
</template>

<script>
export default {
  methods: {
    printDocument() {
      // 获取要打印的HTML元素内容
      const printableContent = this.$refs.printableArea.innerHTML

      // 创建一个新的iframe用于打印
      const iframe = document.createElement('iframe')
      iframe.style.display = 'none'
      document.body.appendChild(iframe)

      // 将内容写入iframe
      const printWindow = iframe.contentWindow
      printWindow.document.open()
      printWindow.document.write(
        '<html lang=""><head><title>打印预览</title></head><body>'
      )
      printWindow.document.write(printableContent)
      printWindow.document.write('</body></html>')
      printWindow.document.close()

      // 执行打印
      printWindow.print()
      console.log(123)

      // 移除iframe
      document.body.removeChild(iframe)
      // setTimeout(() => {
      //   document.body.removeChild(iframe)
      // }, 1000)
    }
  }
}
</script>
